<?php

namespace common\helpers;

use Yii;
use yii\helpers\BaseIpHelper;
use yii\helpers\Json;
use yii\base\Exception;

/**
 * Class IpHelper provides a set of IP-related static methods.
 *
 * Methods expect correct IP addresses.
 * To validate IP addresses use [[\yii\validators\IpValidator|IpValidator]].
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class IpHelper extends BaseIpHelper {

    /**
     * IP地址转换成长整型格式
     * @param string $ip
     * @param boolean $unsigned
     * @return integer
     */
    public static function ip2long($ip, $unsigned = true) {
        $long = ip2long($ip);
        if ($unsigned == true) {
            return sprintf('%u', $long);
        }
        return $long;
    }

    /**
     * 长整型数字格式成IP地址
     * @param integer $long
     * @param bool $simple
     * @return string IP
     */
    public static function long2ip($long, $simple = true) {
        $ip = long2ip($long);
        if ($simple === true) {
            return $ip;
        }
        $info = static::info($ip);
        if ($info) {
            $ip .= '（' . $info . '）';
        }
        return $ip;
    }

    /**
     * 长整型数字格式成IP地址
     * @param integer $long
     * @param bool $simple
     * @return string IP
     */
    public static function info($ip) {
        $key = 'IPDATA' . $ip;
        $cache = Yii::$app->cache;
        $_ip = $cache->get($key);
        if (!$_ip) {
            try {
                $url = "http://ip-api.com/json/" . $ip;
                /* @var $curl \common\components\http\Curl */
                $curl = Yii::$app->curl;
                $curl->setGetParams([
                    'lang' => 'zh-CN'
                ]);
                $data = $curl->get($url);
//                $remote = file_get_contents($url);
//                $data = Json::decode($remote);
                if (!empty($data) && isset($data['status']) && $data['status'] == 'success') {
                    $result = array_filter([
                        ArrayHelper::getValue($data, 'country', ''),
                        ArrayHelper::getValue($data, 'regionName', ''),
                        ArrayHelper::getValue($data, 'city', ''),
                        str_ireplace('XX', '', ArrayHelper::getValue($data, 'county', ''))
                    ]);
                    $_ip = implode(' ', $result);
                    $cache->set($key, $_ip);
                }
            } catch (Exception $e) {
                Yii::error($e->getMessage());
            }
        }
        return $_ip;
    }

    /**
     * 长整型数字格式成IP地址
     * @param boolean $long
     * @return integer user IP
     */
    public static function ip($long = true) {
        $ip = Yii::$app->request->userIP;
        if ($long) {
            return static::ip2long($ip);
        }
        return $ip;
    }

    /**
     * @return mixed
     */
    public static function getServerIp() {
        $ipPython = Yii::getAlias('@common/data/python/ip.py');
        $data = [];
        exec("python3 $ipPython", $data);
        return array_pop($data);
    }

    /**
     * 获取客户端的真实IP
     * @return string 真实IP地址
     */
    public static function getRealIp($long = false) {
        if (getenv('HTTP_X_REAL_IP')) {
            $ip = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $remote_addr = getenv("HTTP_X_FORWARDED_FOR");
            $tmp_ip = explode(",", $remote_addr);
            $ip = $tmp_ip[0];
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = Yii::$app->request->userIP;
        }
        if ($long) {
            return static::ip2long($ip);
        }
        return $ip;
    }

}
